<?php
/**
 * @Author:      famous
 * @DateTime:    2017-05-12 11:12:22
 * @Description: 用于 scs 企业用户管理
 */
class ScsCustomerController extends BaseController {
    /*
     * 身份证检查
     * */
    public function check(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id_card' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $id_card = Input::get('id_card');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

            try{
                $count = Users::where('id_card',$id_card)->count();
                if($count > 0){
                    $response = array('code' => -1, 'msg' => '该身份证已被认证', 'result' => array());
                }else{
                    $response = array('code' => 0, 'msg' => '成功', 'result' => array('id_card' => $id_card));
                }

            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"model" => "customer", "event" => "store", 'input' =>Input::all() ,"exception" => $e));
                return false;
            }

        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "customer", "event" => "check", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      lyt
     * @DateTime:  2017-05-24 09:45:54
     * @Description: 发短信验证信息
     */
    public function sendMessage(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "phone"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $phone=Input::get('phone');
            $area='';
            $time_out_default = Config::get("user.time_out_default");

            //检查手机号是否下发验证码
            $record = UserCheckCodeUpgrade::where("business_type","change_phone")->where("phone",$phone)->first();
            if($record){ //有记录
                //判断是否超时
                if( time() < Common::datetime2Num($record->out_time_at) ){ //没有超过时限
                    try {
                        $sms_send_record_id = Sms::send_message($area,$phone,'您好，更换电话验证码'.$record->check_code);
                    } catch (Exception $e) {
                        Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                        $response = Lang::get("error.user_sms_check_code_send_error_1003");
                        break;
                    }
                    $response = array(
                        'code' => 0,
                        'msg' => 'ok',
                        'result' => array(
                            'out_time' => Common::datetime2Num($record->out_time_at) - time(),
                        ));
                    break;
                }else{ //超过限时
                    UserCheckCodeUpgrade::where("business_type","change_phone")->where("phone",$phone)->delete();
                }
            }
            //超过时限和没有记录
            //生成验证码
            $check_code = Common::generateCode();
            //调用短信网关发送短信
            try {
                $sms_send_record_id = Sms::send_message($area,$phone,'您好，更换电话验证码'.$check_code);
            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_send_error_1003");
                break;
            }
            $record = new UserCheckCodeUpgrade;
            $record->business_type="change_phone";
            $record->business_id="";
            $record->phone=$phone;
            $record->area="";
            $record->check_code=$check_code;
            $record->out_time_at=Common::num2DateTime(time() + $time_out_default);
            $record->send_id=$sms_send_record_id;
            $record->save();
            
            $response['result'] = array('out_time' => $time_out_default);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 修改
     * */
    /**
     * @Author:      lyt
     * @DateTime:  2017-05-24 09:38:17
     * @Description: 添加 电话有效性验证 验证码验证
     */
    public function update(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $user_id = Input::get('user_id');
            $name = Input::get('name');
            $phone = Input::get('phone');
            $sex = Input::get('sex');
            $id_card = Input::get('id_card');
            $code = Input::get('code');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            if($phone ){//如果修改电话验证验证码 他验证电话是否重复
                $tu=Users::where('phone',$phone )->first();
                if($tu){
                    $response = Lang::get("scs_error.user_error_21010");
                    break;
                }
                $record = UserCheckCodeUpgrade::where("business_type","change_phone")->where("phone",$phone)->first();
                if(is_null($record)){ //没有记录
                    $response = Lang::get("error.user_login_checkcode_null_1012");
                    break;
                }
                //校验是否超过时限
                if( time() > Common::datetime2Num($record->out_time_at) ){
                    $response = Lang::get("error.user_login_checkcode_timeout_1013");
                    break;
                }
            
                //校验验证码是否匹配
                if($record->check_code != $code){
                    $response = Lang::get("error.user_login_checkcode_error_1014");
                    break;
                }
            }
            try{
                // if($id_card != '') {
                //     $count = Users::where('id_card',$id_card)->where("id","!=",$user_id)->count();
                //     if($count > 0){
                //         $response = array('code' => -1, 'msg' => '该身份证已被认证', 'result' => array());
                //         break;
                //     }
                // }
                
                $user = Users::where('id',$user_id)->first();
                if(is_null($user)){
                    $response = array('code' => -1, 'msg' => 'user not exist.', 'result' => array());
                }else{
                    if($name != '') $user->real_name = $name;
                    if($phone != '') $user->phone = $phone;
                    if($sex != '') $user->sex = $sex;
                    if($id_card != '') $user->id_card = $id_card;
                    $user->save();
                    $result = array('user_id' => $user->id);
                    $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
                }


            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"model" => "customer", "event" => "store", 'input' =>Input::all() ,"exception" => $e));
                return false;
            }

        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "customer", "event" => "store", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /*
     * 保存
     * */
    public function store(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'name' => 'required',
                'phone' => 'required',
                'sex' => 'required',
//                'car_no' => 'required',
//                'vin' => 'required',
//                'car_model_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $name = Input::get('name');
            $phone = Input::get('phone');
            $sex = Input::get('sex');
            //$car_no = Input::get('car_no');
            //$vin = Input::get('vin');
            //$car_model_id = Input::get('car_model_id');

            $id_card = Input::get('id_card');
            //$start_off_time = Input::get('start_off_time');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            // if($id_card){
            //     $count = Users::where('id_card',$id_card)->count();
            //     if($count > 0){
            //         $response = array('code' => -1, 'msg' => '该身份证已被认证', 'result' => array());
            //         break;
            //     }
            // }
            $count = Users::where('phone',$phone)->count();
            if($count > 0){
                $response = array('code' => -1, 'msg' => 'user have exists.', 'result' => array());
            }else{
                try{
                    $user = new Users();
                    $user->phone = $phone;
                    $user->sex = $sex;
                    $user->real_name = $name;
                    $user->status = 1;
                    $user->id_card = $id_card;
                    $user->register_source_id = 14;
                    $user->member = Config::get('user.def_member');
                    $user->save();

                    /**20170712 去掉车辆信息**/
//                    $user_car_info = new UserCarInfo();
//                    $user_car_info->car_no = $car_no;
//                    $user_car_info->user_id = $user->id;
//                    $user_car_info->status = 1;
//                    $user_car_info->car_model_id = $car_model_id;
//                    $user_car_info->vin_code = $vin;
//                    $user_car_info->start_off_time = $start_off_time;
//                    $user_car_info->save();

                    Account::get_account_no($user->id);
                    $result = array('user_id' => $user->id);

                } catch (Exception $e) {
                    Log::error("error", array("system" => "scs" ,"model" => "customer", "event" => "store", 'input' =>Input::all() ,"exception" => $e));
                    return false;
                }
                $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
            }
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "customer", "event" => "store", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 企业详细信息
     * http://api.anhui.com/v1/scs/customer/detail?token=b5ce501fdbf0ad0436a89ac8cbaef1f6&user_id=1000010444
     * */
    public function detail(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $user_id = Input::get("user_id");

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

            $select_arr = [
                'users.id', 'users.id_card', 'users.real_name', 'users.status', 'users.phone', 'users.sex', 
                'user_account.balance as balance', 'user_account.credit as credit', 
                'user_label_activity_type.name as user_label_activity',
                'users.experience', 'member_ordinary.name AS member_level_name', 'member_ordinary.dis AS member_dis',
            ];
            $customers = Users::orderby("users.created_at","desc")
                    ->leftJoIn("user_account","users.id","=","user_account.user_id")
                    ->leftJoIn("user_label_activity","user_label_activity.user_id","=","users.id")
                    ->leftJoIn("user_label_activity_type","user_label_activity_type.id","=","user_label_activity.lable_id")
                    ->leftJoin('member_ordinary', 'users.member', '=', 'member_ordinary.id')
                    //->select("users.id","users.id_card",'users.real_name','users.status','users.phone','users.sex',"user_account.balance as balance","user_account.credit as credit","user_label_activity_type.name as user_label_activity")
                    ->select($select_arr)
                    ->where('users.type',1)
                    ->where('users.id',$user_id)
                    ->get()
                    ->toArray();
            
            foreach ($customers as &$_customer){
                $weixin_user = DB::select('select * from user_weixin_add where user_id = ' . $_customer['id']);
                if(sizeof($weixin_user) > 0){
                    $_customer['wechat'] = 1;
                    $_customer['head_img'] = $weixin_user[0]->avatar;
                }else{
                    $_customer['wechat'] = 0;
                    $_customer['head_img'] = '';
                }

                $not_come_count = Orders::where("place",2)->where('user_id',$_customer['id'])->where("order_type",1)->whereIn("status",array(1310))->where('order_source',10)->count();
                $_customer['not_come_count'] = $not_come_count;

                $complete_amount = Orders::whereIn('status',array(1018,1017,1217,1317,1417))->where('user_id',$_customer['id'])->sum('payable_amount');
                $return_amount = ReturnOrder::LeftJoin('orders','return_order.order_id','=','orders.order_id')
                    ->where('orders.user_id',$_customer['id'])->where('return_order.status',1)->sum('return_order.amount');
                $_customer['consume_amount'] = ($complete_amount - $return_amount) / 100;

                //用户画像
                $user_label = Labels::leftJoin('user_label','user_label.label_id','=','labels.id')
                    ->select('labels.name')
                    ->where('user_label.user_id',$_customer['id'])
                    ->distinct()
                    ->get()
                    ->toArray();
                $_customer['label'] = $user_label;
                
                //查询用户的临时会员    start
                $mtu_member = MemberTemporaryUser::leftJoin("member_temporary","member_temporary.id","=","member_temporary_user.member_temporary_id")
                        ->where("member_temporary_user.user_id",$_customer['id'])
                        ->where("member_temporary_user.end_time",">",Common::currentTimeString())
                        ->orderBy("member_temporary.dis","asc")
                        ->select("member_temporary.dis","member_temporary.name","member_temporary_user.created_at")
                        ->first();
                if($mtu_member){
                    $pt_dis = isset($_customer['member_dis']) ? $_customer['member_dis'] : 1;   //普通会员折扣
                    $ls_dis = isset($mtu_member->dis) ? $mtu_member->dis : 1;                   //临时折扣
                    if($ls_dis < $pt_dis){
                        $_customer['experience'] = '';
                        $_customer['member_level_name'] = $mtu_member->name;
                        $_customer['member_dis'] = $ls_dis;
                    }
                }
                //查询用户的临时会员    end
            }

            $count = count($customers);
            $result = array(
                'count' => $count,
                'customers' => $customers
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "customer", "event" => "detail", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      famous
     * @DateTime:    2017-05-12 11:12:22
     * @Description: 企业用户列表
     * http://api.anhui.com/v1/scs/customer/lists?token=b5ce501fdbf0ad0436a89ac8cbaef1f6
     */
    public function lists()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $page_size = Input::get("page_size", 10);
            $page = Input::get("page", 0);

            $car_no = Input::get('car_no');
            $phone = Input::get('phone');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

            $customers = Users::orderby("users.created_at","desc")
                ->leftJoIn("user_account","users.id","=","user_account.user_id")
                ->select("users.id",'users.phone as real_name','users.status','users.id_card',"user_account.balance as balance","user_account.credit as credit")
                ->where('users.type',1)
                ->where('users.id','!=','1000000000')
                ->skip($page_size*($page-1))
                ->take($page_size);

            $count = Users::orderby("users.created_at","desc")
                ->leftJoIn("user_account","users.id","=","user_account.user_id")
                ->select("users.id",'users.real_name','users.status',"user_account.balance as balance","user_account.credit as credit")
                ->where('users.type',1)
                ->where('users.id','!=','1000000000');

            if($car_no != ''){
                $car_nos = UserCarInfo::where('car_no',$car_no)->where('status',1)->select(array('user_id'))->distinct()->get()->toArray();
                $customers->whereIn('users.id',$car_nos);
                $count->whereIn('users.id',$car_nos);
            }
            if($phone != ''){
                $customers->where('users.phone','like','%'.$phone."%");
                $count->where('users.phone','like','%'.$phone."%");
            }
            $customers = $customers->get()->toArray();
            $count = $count->count();

            foreach ($customers as &$_customer){
                if(strlen($_customer['id_card']) > 0) $_customer['authentication'] = 1; else $_customer['authentication'] = 0;
                $_customer['balance'] = $_customer['balance']/100;
                $_customer['credit'] = $_customer['credit']/100;
                if(strlen($_customer['real_name'])>7){
                    $_customer['real_name']=substr_replace($_customer['real_name'], '****', 3, 4);
                }
            }

            $result = array(
                'count' => $count,
                'customers' => $customers
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "customer", "event" => "lists", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

}